package com.jthinker.web.controller.admin;

import com.jthinker.bean.enu.CommentStatus;
import com.jthinker.bean.vo.Constant;
import com.jthinker.bean.vo.QueryResult;
import com.jthinker.bean.vo.SearchFilter;
import com.jthinker.service.CategoryService;
import com.jthinker.service.PostService;
import com.jthinker.web.controller.common.BaseController;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * User: Gang Chen
 * Date: 2015/4/12 21:11
 */
@Controller
@RequestMapping("/post")
public class PostController extends BaseController
{
    @Resource
    private PostService postService;

    @Resource
    private CategoryService categoryService;

    @RequestMapping
    public String view()
    {
        return "post/postList";
    }

    @RequestMapping("/list")
    @ResponseBody
    public Map<String, Object> list(HttpServletRequest request)
    {
        SearchFilter filter = getSearchFilter(request);
        QueryResult<Map<String, Object>> result = postService.queryGrid(filter);
        return getSuccessMessage(result);
    }

    @RequestMapping({ "/newPost", "/modifyPost" })
    public String newPost(Model model, @RequestParam(required = false) String id)
    {
        if (StringUtils.isNoneBlank(id))
        {
            Map<String, Object> record = postService.read(id);
            model.addAttribute("record", record);
        }
        List<Map<String, Object>> categorys = categoryService.findAll();
        model.addAttribute("categorys", categorys);
        return "post/postView";
    }

    @RequestMapping("/postAddOrUpdate")
    public String postAdd(HttpServletRequest request) throws UnsupportedEncodingException
    {
        String id = request.getParameter("id");
        String title = request.getParameter("title");
        String content = request.getParameter("content");
        String excerpt = request.getParameter("excerpt");
        String commentStatusRaw = request.getParameter("commentStatus");

        String categoryId = request.getParameter("categoryId");

        CommentStatus commentStatus = CommentStatus.parse(commentStatusRaw);
        String name = URLEncoder.encode(title, Constant.DEFAULT_ENCODING);

        Date postDate = DateTime.now().toDate();
        Date postModified = postDate;

        //自动生成摘要
        if (StringUtils.isBlank(excerpt))
        {
            excerpt = getExcerpt(content);
        }

        Map<String, Object> record = new HashMap<String, Object>();
        record.put("content", content);
        record.put("title", title);
        record.put("excerpt", excerpt);
        record.put("comment_status", commentStatus.getKey());
        record.put("name", name);

        record.put("category_id", categoryId);
        try
        {
            if (StringUtils.isBlank(id))
            {
                record.put("user_id", getCurrentUserId(request));
                record.put("post_date", postDate);
                record.put("post_modified", postModified);
                postService.create(record);
            }
            else
            {
                record.put("post_modified", postModified);
                postService.update(record, id);
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
            return "post/postView";
        }

        return "redirect:" + Constant.URL_ADMIN + "/post";

    }

    @RequestMapping("/delete")
    @ResponseBody
    public Map<String, Object> delete(@RequestParam(value = "id", required = false) String id)
    {
        if (isEmpty(id))
        {
            return getFailMessage("请选择行!");
        }

        try
        {
            postService.delete(id);
        }
        catch (Exception e)
        {
            e.printStackTrace();
            return getFailMessage("删除失败!");
        }

        return getSuccessMessage("删除成功!");
    }

    private String getExcerpt(String content)
    {
        return StringUtils
                .substring(content.replaceAll("<.*?>", "").replaceAll(" ", "").replaceAll("<.*?", ""), 0, Constant.DEFAULT_EXCERPT_LENGTH);
    }
}
